package com.ncmmall.application.business.supplier;

import com.feijin.commons.lang.Randoms;
import com.feijin.commons.securitys.MD5HashUtils;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.merchant.MerchantEnterpriseInfo;
import com.ncmmall.domain.business.merchant.MerchantEnterpriseInfoRepository;
import com.ncmmall.domain.business.merchant.MerchantGoodsChannel;
import com.ncmmall.domain.business.merchant.MerchantGoodsChannelRepository;
import com.ncmmall.domain.business.merchant.MerchantIndividualInfo;
import com.ncmmall.domain.business.merchant.MerchantIndividualInfoRepository;
import com.ncmmall.domain.business.merchant.MerchantPersonalInfo;
import com.ncmmall.domain.business.merchant.MerchantPersonalInfoRepository;
import com.ncmmall.domain.business.merchant.QMerchantGoodsChannel;
import com.ncmmall.domain.security.role.QRole;
import com.ncmmall.domain.security.role.Role;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.domain.security.user.WebUserRepository;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import com.google.common.primitives.Longs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author linxs
 *         供应商管理
 */
@Service
@Transactional
public class SupplierApplication {

    private static final Logger log = LoggerFactory.getLogger(SupplierApplication.class);

    @Autowired
    private WebUserRepository supplierRepository;

    @Autowired
    private MerchantEnterpriseInfoRepository enterpriseInfoRepository;

    @Autowired
    private MerchantIndividualInfoRepository individualInfoRepository;

    @Autowired
    private MerchantPersonalInfoRepository personalInfoRepository;

    @Autowired
    private MerchantGoodsChannelRepository supplierGoodsChannelRepository;


    @Autowired
    private QueryChannelService queryChannelService;


    /**
     * /**
     * 禁用账号
     *
     * @param user
     */
    public void disable(WebUser user) {
        user.setAccountNonLocked(false);
        supplierRepository.save(user);
    }

    /**
     * 启用账号
     *
     * @param user
     */
    public void enabled(WebUser user) {
        user.setAccountNonLocked(true);
        supplierRepository.save(user);
    }

    /**
     * 添加供应商
     *
     * @param supplier
     */
    public WebUser createSupplier(WebUser supplier) {

        if (supplier.isEnterpriseMerchant()) {
            MerchantEnterpriseInfo enterpriseInfo = supplier.getMerchantEnterpriseInfo();
            enterpriseInfoRepository.save(enterpriseInfo);
            supplier.setMerchantEnterpriseInfo(enterpriseInfo);
            supplier.setMerchantIndividualInfo(null);
            supplier.setMerchantPersonalInfo(null);
        }

        if (supplier.isIndividualMerchant()) {
            MerchantIndividualInfo individualHouseholdInfo = supplier.getMerchantIndividualInfo();
            individualInfoRepository.save(individualHouseholdInfo);
            supplier.setMerchantIndividualInfo(individualHouseholdInfo);
            supplier.setMerchantEnterpriseInfo(null);
            supplier.setMerchantPersonalInfo(null);
        }

        if (supplier.isPersonalMerchant()) {
            MerchantPersonalInfo personalInfo = supplier.getMerchantPersonalInfo();
            personalInfoRepository.save(personalInfo);
            supplier.setMerchantPersonalInfo(personalInfo);
            supplier.setMerchantEnterpriseInfo(null);
            supplier.setMerchantIndividualInfo(null);
        }

        String userNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + Randoms.generateDigitalString(5);
        supplier.setUserNo(userNo);
        supplier.setRole(queryChannelService.findOne(QRole.role.name.eq("SUPPLIER"), Role.class));
        String passwordAsMd5 = MD5HashUtils.asMD5(MD5HashUtils.MD5(supplier.getPassword()), supplier.getUsername());
        supplier.setPassword(passwordAsMd5);
        supplier.setAccountNonLocked(true);
        supplier.setAccessToken(MD5HashUtils.md5(passwordAsMd5, supplier.getUsername()));
        supplier.setCreateTime(new Timestamp(System.currentTimeMillis()));
        supplier.setMerchantEnterTime(supplier.getCreateTime());
        supplier.setAccountNonLocked(false);
        supplier.setMerchantCheckStatus(1);
        supplierRepository.save(supplier);

        List<String> supplierGoodsChannelIds = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(supplier.getMerchantGoodsChannelsData());
        for (String item : supplierGoodsChannelIds) {
            MerchantGoodsChannel goodsChannel = new MerchantGoodsChannel();
            goodsChannel.setChannel(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(Longs.tryParse(item)), GoodsChannel.class));
            goodsChannel.setMerchant(supplier);
            supplierGoodsChannelRepository.save(goodsChannel);
        }

        return supplier;

    }

    /**
     * 批量启用
     *
     * @param suppliers
     */
    public void enables(List<WebUser> suppliers) {
        for (WebUser supplier : suppliers) {
            enabled(supplier);
        }
    }

    /**
     * 批量禁用
     *
     * @param suppliers
     */
    public void disables(List<WebUser> suppliers) {
        for (WebUser supplier : suppliers) {
            disable(supplier);
        }
    }

    /**
     * 编辑供应商信息
     *
     * @param supplier
     */
    public WebUser modifySupplier(WebUser params) {

        WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(params.getId()), WebUser.class);

        if (params.isEnterpriseMerchant()) {
            MerchantEnterpriseInfo enterpriseInfo = params.getMerchantEnterpriseInfo();
            enterpriseInfoRepository.save(enterpriseInfo);
            supplier.setMerchantEnterpriseInfo(enterpriseInfo);
            supplier.setMerchantIndividualInfo(null);
            supplier.setMerchantPersonalInfo(null);
        }

        if (params.isIndividualMerchant()) {
            MerchantIndividualInfo individualHouseholdInfo = params.getMerchantIndividualInfo();
            individualInfoRepository.save(individualHouseholdInfo);
            supplier.setMerchantIndividualInfo(individualHouseholdInfo);
            supplier.setMerchantEnterpriseInfo(null);
            supplier.setMerchantPersonalInfo(null);
        }

        if (params.isPersonalMerchant()) {
            MerchantPersonalInfo personalInfo = params.getMerchantPersonalInfo();
            personalInfoRepository.save(personalInfo);
            supplier.setMerchantPersonalInfo(personalInfo);
            supplier.setMerchantEnterpriseInfo(null);
            supplier.setMerchantIndividualInfo(null);
        }

        supplier.setShopName(params.getShopName());
        supplier.setRealName(params.getRealName());
        supplier.setEmail(params.getEmail());
        supplier.setMobile(params.getMobile());
        supplier.setWechat(params.getWechat());
        supplier.setQq(params.getQq());
        supplier.setMainType(params.getMainType());

        supplier.setBankName(params.getBankName());
        supplier.setBankCardNo(params.getBankCardNo());
        supplier.setBankAccountHolder(params.getBankAccountHolder());
        supplier.setBankCity(params.getBankCity());
        supplier.setBankProvince(params.getBankProvince());
        supplier.setBankMobile(params.getBankMobile());
        supplier.setBankSubBranchName(params.getBankSubBranchName());

        supplier.setMerchantInvoiceTFN(params.getMerchantInvoiceTFN());
        supplier.setMerchantInvoiceTitle(params.getMerchantInvoiceTitle());
        supplier.setMerchantInvoiceTitleType(params.getMerchantInvoiceTitleType());


        supplierRepository.save(supplier);

        List<MerchantGoodsChannel> channels = queryChannelService.findAll(QMerchantGoodsChannel.merchantGoodsChannel.merchant.id.eq(params.getId()), MerchantGoodsChannel.class);
        supplierGoodsChannelRepository.delete(channels);

        List<String> supplierGoodsChannelIds = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(params.getMerchantGoodsChannelsData());
        for (String item : supplierGoodsChannelIds) {
            MerchantGoodsChannel goodsChannel = new MerchantGoodsChannel();
            goodsChannel.setChannel(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(Longs.tryParse(item)), GoodsChannel.class));
            goodsChannel.setMerchant(supplier);
            supplierGoodsChannelRepository.save(goodsChannel);
        }

        return supplier;
    }

    /**
     * 审核供应商
     *
     * @param supplier
     */
    public void checkMerchant(WebUser params) {
        WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(params.getId()), WebUser.class);
        supplier.setMerchantCheckStatus(params.getMerchantCheckStatus());
        supplier.setMerchantCheckNote(params.getMerchantCheckNote());
        supplierRepository.save(supplier);

    }

    /**
     * 设置自提地址
     *
     * @param supplier
     * @param address
     */
    public void setterShippingAddress(WebUser supplier, String address) {
        supplier.setWarehouseAddress(address);
        supplierRepository.save(supplier);
    }

    /**
     * 设为自营
     *
     * @param supplier
     */
    public void selfSupport(WebUser supplier) {
        supplier.setSelfSupport(1);
        supplierRepository.save(supplier);
    }

    /**
     * 取消自营
     *
     * @param supplier
     */
    public void cancelSelfSupport(WebUser supplier) {
        supplier.setSelfSupport(0);
        supplierRepository.save(supplier);
    }

    public WebUser modifyMerchantInfo(WebUser params) {
        WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(params.getId()), WebUser.class);

        if (supplier.isEnterpriseMerchant()) {
            MerchantEnterpriseInfo enterpriseInfo = params.getMerchantEnterpriseInfo();
            enterpriseInfoRepository.save(enterpriseInfo);
            supplier.setMerchantEnterpriseInfo(enterpriseInfo);
            supplier.setMerchantIndividualInfo(null);
            supplier.setMerchantPersonalInfo(null);
        }

        if (supplier.isIndividualMerchant()) {
            MerchantIndividualInfo individualHouseholdInfo = params.getMerchantIndividualInfo();
            individualInfoRepository.save(individualHouseholdInfo);
            supplier.setMerchantIndividualInfo(individualHouseholdInfo);
            supplier.setMerchantEnterpriseInfo(null);
            supplier.setMerchantPersonalInfo(null);
        }

        if (supplier.isPersonalMerchant()) {
            MerchantPersonalInfo personalInfo = params.getMerchantPersonalInfo();
            personalInfoRepository.save(personalInfo);
            supplier.setMerchantPersonalInfo(personalInfo);
            supplier.setMerchantEnterpriseInfo(null);
            supplier.setMerchantIndividualInfo(null);
        }

        supplier.setShopName(params.getShopName());
        supplier.setRealName(params.getRealName());
        supplier.setEmail(params.getEmail());
        supplier.setMobile(params.getMobile());
        supplier.setWechat(params.getWechat());
        supplier.setQq(params.getQq());
        supplier.setMainType(params.getMainType());
        supplier.setShopBanner(params.getShopBanner());

        supplier.setBankName(params.getBankName());
        supplier.setBankCardNo(params.getBankCardNo());
        supplier.setBankAccountHolder(params.getBankAccountHolder());
        supplier.setBankCity(params.getBankCity());
        supplier.setBankProvince(params.getBankProvince());
        supplier.setBankMobile(params.getBankMobile());
        supplier.setBankSubBranchName(params.getBankSubBranchName());

        supplierRepository.save(supplier);

        return supplier;
    }

    /**
     * 重置密码
     *
     * @param supplier
     * @param password
     */
    public void modifyPassword(WebUser supplier, String password) {
        String passwordAsMd5 = MD5HashUtils.asMD5(password, supplier.getUsername());
        supplier.setPassword(passwordAsMd5);
        supplierRepository.save(supplier);
    }
}
